import React, { useState } from "react";
import config from "../../../config/config";
import * as userService from '../services/userService';

export default function useUserState() {

    const [loading, setLoading] = useState(false);
    const [currentPage, setCurrentPage] = useState(0);
    const [pageSize, setPageSize] = useState(config.defalut_page_size);
    const [total, setTotal] = useState(0);
    const [userList, setUserList] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);
    const [searchParams, setSearchParams] = useState({});
    const [userModalVisible, setUserModalVisible] = useState(false);
    const [userRecord, setUserRecord] = useState({});

    const loadUserPage = (params) => {
        userService.getUserPage(params).then(res => {
            if (res.code == 200) {
                const data = res.data;
                setTotal(data.total);
                setUserList(data.records);
            }
        })
    }

    const addSystemUser = (values) => {
        values.current_page = currentPage;
        values.page_size = pageSize;
        userService.addUser(values).then(res => {
            if (res.code == 200) {
                const data = res.data;
                setTotal(data.total);
                setUserList(data.records);
                setUserModalVisible(false);
            }
        });
    }

    const deleteSystemUser = (values = {}) => {
        values.current_page = currentPage;
        values.page_size = pageSize;
        values.ids = selectedRowKeys.join(",")
        userService.deleteUser(values).then(res => {
            if (res.code == 200) {
                const data = res.data;
                setTotal(data.total);
                setUserList(data.records);
            }
        });
    }

    const updateSystemUser = (values = {}) => {
        values.current_page = currentPage;
        values.page_size = pageSize;
        values.ids = selectedRowKeys.join(",")
        userService.updateUser(values).then(res => {
            if (res.code == 200) {
                const data = res.data;
                setTotal(data.total);
                setUserList(data.records);
                setUserModalVisible(false);
            }
        });
    }

    return {
        loading, setLoading,
        currentPage, setCurrentPage,
        pageSize, setPageSize,
        total, setTotal,
        userList, setUserList,
        selectedRowKeys, setSelectedRowKeys,
        selectedRows, setSelectedRows,
        searchParams, setSearchParams,
        userModalVisible, setUserModalVisible,
        loadUserPage, addSystemUser, deleteSystemUser,
        userRecord, setUserRecord, updateSystemUser
    };
}
